<template>
  <basic-container>
    <div class="app-container">
      <el-row :gutter="40">
        <el-col :span="4" style="position:relative;">
          <el-input v-model="filterText" placeholder="输入名称进行过滤" />
          <div ref="filterTreeWrapper" class="filter-tree-wrapper">
            <el-tree
              v-loading="listCatetory"
              ref="tree2"
              :data="data2"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              highlight-current
              class="filter-tree"
              default-expand-all
              @current-change="onClickNode"
            />
          </div>
        </el-col>
        <el-col :span="20">
          <div class="filter-container">
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              icon="el-icon-plus"
              @click="addRow"
            >添加</el-button>
            <el-input
              v-model="listQuery.title"
              size="small"
              clearable
              placeholder="分类名称"
              style="width: 220px;"
              class="filter-item"
              @keyup.enter.native="getList"
            />
            <el-select
              v-model="listQuery.status"
              size="small"
              placeholder="上线状态"
              class="filter-item"
              clearable
            >
              <el-option
                v-for="(opt) in $constants.goodsStatusOptions"
                :key="opt.value"
                :label="opt.title"
                :value="opt.value"
              />
            </el-select>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="getList"
            >搜索</el-button>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="danger"
              icon="el-icon-edit"
              @click="handleBatchOffline"
            >批量下线</el-button>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              icon="el-icon-edit"
              @click="handleBatchOnline"
            >批量上线</el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="list"
            border
            fit
            @selection-change="handleSelectionChange"
            :height="tableHeight"
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="PATH" width="90px" align="center">
              <template slot-scope="scope">{{ scope.row.orgin_path }}</template>
            </el-table-column>
            <el-table-column label="分类名称" width="120px" align="center">
              <template slot-scope="scope">{{ scope.row.title }}</template>
            </el-table-column>
            <el-table-column label="分类路径" width="220" align="left">
              <template slot-scope="scope">{{ scope.row.path_name }}</template>
            </el-table-column>
            <el-table-column label="封面" width="120px" align="center">
              <template slot-scope="scope">
                <img :src="scope.row.cover|imgUrl" alt class="cover-img" style="height:80px;" />
              </template>
            </el-table-column>
            <el-table-column label="状态" width="120px" align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.status==1?'success':'danger'"
                >{{ scope.row.status==1?'已上线':'已下线' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="排序" width="90px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.sort }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="170px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.create_time }}</span>
              </template>
            </el-table-column>
            <el-table-column label="修改时间" width="170px" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.modify_time }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              min-width="240"
              class-name="small-padding"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.status==0"
                  type="primary"
                  size="mini"
                  @click="setOnline(scope.row)"
                >上线</el-button>
                <el-button
                  v-if="scope.row.status==1"
                  type="danger"
                  size="mini"
                  @click="setOffline(scope.row)"
                >下线</el-button>
                <el-button type="primary" size="mini" @click="editRow(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              :current-page.sync="listQuery.pageNo"
              :page-sizes="[10,20,30, 50]"
              :page-size="listQuery.pageSize"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>

          <el-dialog append-to-body :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="700px">
            <el-form
              ref="dataForm"
              :rules="rules"
              :model="temp"
              label-position="left"
              label-width="120px"
              style="margin-left:50px;margin-right:50px;"
            >
              <el-form-item label="分类名称" prop="title">
                <el-input v-model="temp.title" placeholder="分类名称" />
              </el-form-item>
              <el-form-item label="父分类">
                <el-cascader
                  :props="defaultProps"
                  :options="categoryOptions"
                  v-model="temp.path"
                  clearable
                  change-on-select
                />
              </el-form-item>
              <!-- <el-form-item label="页面路径" prop="page_path">
              <el-input v-model="temp.page_path" placeholder="页面路径"/>
              </el-form-item>-->
              <el-form-item label="排序号" prop="sort">
                <el-input-number v-model="temp.sort" placeholder="排序号" />
              </el-form-item>
              <el-form-item label="封面" prop="cover">
                <el-upload
                  :action="UPLOAD_URL"
                  :show-file-list="false"
                  :headers="getHeaders()"
                  :on-success="handleAvatarSuccess('cover')"
                  :before-upload="beforeAvatarUpload"
                  class="avatar-uploader"
                >
                  <img v-if="temp.cover" :src="temp.cover|imgUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
            </div>
          </el-dialog>
        </el-col>
      </el-row>
    </div>
  </basic-container>
</template>

<script>
import { bannerPosTypes } from "../../constants/constants";
import * as apiObj from "@/api/category";

export default {
  filters: {
    bannerPosFilter(value) {
      const b = bannerPosTypes.filter(el => el.value === value)[0];
      if (b) {
        return b.title;
      }
      return ""; // #endregion
    }
  },
  data() {
    return {
      list: null,
      currentSelectedNode: null,
      defaultProps: {
        children: "children",
        label: "title",
        value: "id"
      },
      filterText: "",
      data2: [],
      listCatetory: false,
      isSubmiting: false,
      isEditing: false,
      bannerPosTypes,
      dialogFormVisible: false,
      pwdDialogFormVisible: false,
      categoryOptions: [],
      listLoading: false,
      temp: {
        img_src: "",
        sort: 0
      },
      total: 0,
      rules: {
        sort: [
          {
            required: true,
            message: "请指定排序号",
            trigger: "change"
          }
        ],
        page_path: [
          {
            required: true,
            message: "请输入页面路径",
            trigger: "change"
          }
        ],
        title: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "change"
          }
        ],
        cover: [
          {
            required: false,
            message: "请上传封面",
            trigger: "change"
          }
        ]
      },
      listQuery: {
        pageNo: 1,
        pageSize: 10
      }
    };
  },
  computed: {
    currentParentName() {
      if (
        this.currentSelectedNode &&
        this.currentSelectedNode.id !== this.temp.id
      ) {
        return this.currentSelectedNode.title;
      }
      return "(无)";
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  mounted() {
    this.$refs.filterTreeWrapper.style.height = window.innerHeight - 200 + "px";
  },
  created() {
    this.getList();
    this.loadAllNodes();
    this.tableHeight = window.innerHeight - 260;
  },

  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleBatchOffline() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm("确认下线选择的分类吗").then(() => {
        apiObj.offline(this.multipleSelection.map(el => el.id)).then(() => {
          this.getList();
          this.success();
        });
      });
    },
    handleBatchOnline() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.confirm("确认上线选择的分类吗").then(() => {
        apiObj.online(this.multipleSelection.map(el => el.id)).then(() => {
          this.getList();
          this.success();
        });
      });
    },
    loadAllNodes() {
      this.listCatetory = true;
      apiObj
        .loadTreeData()
        .then(data => {
          this.listCatetory = false;
          this.categoryOptions = data;
          this.data2 = [
            {
              id: 0,
              title: "ROOT",
              children: this.categoryOptions
            }
          ];
        })
        .catch(() => {
          this.listCatetory = false;
        });
    },
    onClickNode(data) {
      this.currentSelectedNode = data;
      this.getList();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    setOnline(row) {
      this.confirm("确认上线该分类吗").then(() => {
        apiObj.online(row.id).then(() => {
          this.getList();
          this.success();
        });
      });
    },
    setOffline(row) {
      this.confirm("确认下线该分类吗").then(() => {
        apiObj.offline(row.id).then(() => {
          this.getList();
          this.success();
        });
      });
    },
    deleteRow(row) {
      this.confirm("确认删除该分类吗").then(() => {
        apiObj.remove(row.id).then(() => {
          this.success();
          this.getList();
          this.loadAllNodes();
        });
      });
    },
    addRow() {
      this.dialogFormVisible = true;
      this.isEditing = false;
      Object.keys(this.temp).forEach(key => {
        if (key === "sort") {
          this.temp[key] = 0;
        } else {
          this.temp[key] = "";
        }
      });

      if (this.currentSelectedNode && this.currentSelectedNode.path) {
        this.temp.path = this.currentSelectedNode.path.replace(/,$/gi,'')
          .split(",")
          .map(el => parseInt(el));
      } else {
        this.temp.path = [];
      }
    },
    editRow(row) {
      this.dialogFormVisible = true;
      this.isEditing = true;
      this.temp = Object.assign({}, row);
    },
    handleCurrentChange(page) {
      this.listQuery.pageNo = page;
      this.getList();
    },
    handleSizeChange(size) {
      this.listQuery.pageSize = size;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      this.listQuery.path = this.currentSelectedNode
        ? this.currentSelectedNode.path
        : '';
      apiObj
        .list(this.listQuery)
        .then(response => {
          this.list = (response.rows || []).map(el => {
            el.orgin_path = el.path;
            if (el.path) {
              el.path = el.path.replace(/-$/gi,'').split("-").map(el => parseInt(el));
              el.path = el.path.slice(0, -1);
            } else {
              el.path = [];
            }
            return el;
          });
          this.total = response.total;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    submitFormAction() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.isSubmiting = true;
          let func;
          if (this.isEditing) {
            func = apiObj.update;
          } else {
            func = apiObj.create;
          }
          func(this.temp)
            .then(() => {
              this.success();
              this.dialogFormVisible = false;
              this.getList();
              this.loadAllNodes();
            })
            .finally(() => {
              this.isSubmiting = false;
            });
        }
      });
    }
  }
};
</script>

<style scoped>
.filter-tree-wrapper {
  overflow: auto;
  margin-top: 20px;
}
</style>
